package main

import (
	"crypto/tls"
	"log"
	"net/http"
	"crypto/x509"
	"io/ioutil"
)

func handler(w http.ResponseWriter, r *http.Request) {
	log.Printf("Served client %s\n", r.TLS.PeerCertificates[0].Subject) // 打印客户端证书信息
	w.Write([]byte("Hello, this is an HTTPS server with mutual TLS!"))
}

func main() {
	cert, err := tls.LoadX509KeyPair("server.crt", "server.key")
	if err != nil {
		log.Fatalf("server: loadkeys: %s", err)
	}

	clientCAs := x509.NewCertPool()
	pemData, err := ioutil.ReadFile("ca.crt")
	if err != nil {
		log.Fatalf("Failed to read CA certificate: %v", err)
	}
	if ok := clientCAs.AppendCertsFromPEM(pemData); !ok {
		log.Fatal("Failed to parse CA certificate")
	}

	config := &tls.Config{
		Certificates: []tls.Certificate{cert},
		ClientAuth:   tls.RequireAndVerifyClientCert,
		ClientCAs:    clientCAs,
	}

	service := ":443"
	server := &http.Server{
		Addr:    service,
		TLSConfig: config,
		Handler: http.HandlerFunc(handler),
	}

	log.Printf("Starting HTTPS server on %s", service)
	err = server.ListenAndServeTLS("", "")
	if err != nil {
		log.Fatalf("ListenAndServe: %v", err)
	}
}
